import 'dart:convert';

import 'package:flutter_jpf_core/network/http_manager.dart' as JPFCore;
import 'package:flutter_jpf_debug/flutter_jpf_debug.dart';
import 'package:dio/dio.dart';

class AppConfig
{
  static void setAppConfig(){

    //网络代理
    JPFCore.HttpManager.config(canProxy: false,proxyHost: "172.16.56.177:8888",interceptor: LogInterceptors());

    JPFCore.HttpManager.getHeaders = (){
      Map map = {"time":DateTime.now()};
      print(map);
      return map;
    };
    Log.config(LogLevel.debug);


    Log.onHandleLog = (LogLevel level,Object message){
      //Log.printToConsole(level, message);
      print("onHandleLog:$message");
      if(Log.dealLevel.index <= level.index){
        Map<String, dynamic> map = {
          "version":	"1.0.0",
          "data":	message,
          "host":	"com.jpf.app",
          "type":	"Error",
          "time":	DateTime.now(),
          "tag":	""
        };
        submitLog(map);
      }
    };
  }

  static submitLog( Map<String, dynamic> map ){

    print(map);
    String url = "https://www.jpfei.top/log/save1.0.0.php";
    Dio().request(
      url,
      queryParameters: map,//new Map<String, dynamic>.from(map),
      options: new Options(method: "POST"),
    );
  }
}


class LogInterceptors extends InterceptorsWrapper {
  @override
  Future onRequest(RequestOptions options) {
    Log.D("【请求url】${options.baseUrl}${options.path}"
        "【请求headers】${options.headers.toString()}"
        "【请求参数query】${options.queryParameters.toString()}"
        "【请求参数data】${jsonEncode(options.data)}");
    return super.onRequest(options);
  }

  @override
  Future onResponse(Response response) {
    RequestOptions options = response.request;
    String msg = "【请求url】${options.baseUrl}${options.path}"
        "【返回headers】${options.headers.toString()}"
        "【请求参数query】${options.queryParameters.toString()}"
        "【请求参数data】${jsonEncode(options.data)}"
        "【返回data】${jsonEncode(response.data)}";
    //msg = "【返回statusCode】${response.statusCode} 【返回headers】${response.headers.toString()} 【返回extra】${response.extra.toString()} 【返回data】${response.data.toString()}";
    Log.D(msg);
    return super.onResponse(response);
  }

  @override
  Future onError(DioError err) {
    RequestOptions options = err.request;
    Log.Er("【请求url】${options.baseUrl}${options.path}"
        "【请求headers】${options.headers.toString()}"
        //"【请求参数query】${options.queryParameters.toString()}"
        "【请求参数data】${jsonEncode(options.data)}"
        "${err.toString()}"
        "${err.response?.toString()}".replaceAll("\n", '\\n'));
    return super.onError(err);
  }
}
